package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.OrderDB;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;

import org.apache.http.Header;

import java.util.List;
import java.util.concurrent.Executors;

public class UpdateOrderTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "UpdateOrderTask";
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有订单列表
            getAllOrder();

        } catch (Exception e) {
            App.isOrderUpdating = false;
            e.printStackTrace();
        }
        return true;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllOrder() {
        try {
            String url = NetUtils.FIND_ALL_ORDER;
            long time = new OrderDB().getMaxModifyTime();
            String path = url + SharedPreference.getPreferString("dealer") + "&employerId=" + SharedPreference.getPreferString("id")
                    + "&userId=" + SharedPreference.getPreferString("id")+ "&modifyTime=" + time;
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            App.isOrderUpdating = true;

            Log.d(TAG, "path :" + path);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "ORDER_ALL:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            JSONObject data = jsonObejct.getJSONObject("data");
                            final List<FindOrderDetail> temList = JSONArray.parseArray(data.getJSONArray("rows").toString(), FindOrderDetail.class);
                            if(temList.size() > 0){
                                //CommUtil.d(App.mContext, TAG, "UpdateOrder:temList=" + temList.size());
                                CommUtil.d(App.mContext, TAG, "List.size()=" + temList.size());
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        OrderDB customerDB = new OrderDB();
                                        if (customerDB.updateAllOrder(temList) == 0) {
                                            //将订单结果更新
                                            App.mOrderList.addAll(temList);
                                            UpdateOrderTask product4 = new UpdateOrderTask();
                                            product4.executeOnExecutor(Executors.newCachedThreadPool());
                                        } else {
                                            App.isOrderUpdating = false;

                                        }
                                    }
                                }).start();
                            }else {
                                App.isOrderUpdating = false;

                            }
                        }else {
                            App.isOrderUpdating = false;

                        }
                    } catch (Exception e) {
                        App.isOrderUpdating = false;

                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    App.isOrderUpdating = false;

                }
            });
        } catch (Exception e) {
            App.isOrderUpdating = false;

            e.printStackTrace();
        }
    }
}
